import logging

from django.http import JsonResponse
from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response, get_ip
from utils.dbutils import DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *
from datetime import datetime, timedelta

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def attends_record(params):
    '''
    打卡
    '''
    dict = {
        "user_id": "user_id",
        "start_or_end": "start_or_end",
        "period_id": "period_id",
        "attend_times": "attend_times",
        "attend_group": "attend_group"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key,val in params.items():
    #     if val is None:
    #         return err_response(210)
    params["user_ip"] = user_ip
    sql_insert = AttendsSqlMap.INSERT_RECORD.format(**params)
    result = mysql_tools.execute_sql(sql_insert, commit=True)
    if isinstance(result, JsonResponse):
        return result
    
    # 获得打卡人的考勤组
    group_sql = AttendsSqlMap.GET_GROUP_BY_USERID.format(**params)
    group = mysql_tools.select_one(group_sql)
    
    later_time = None
    absent_time = None
    if group.get("set_absent"):
        # 获得迟到时间
        later_time = group.get("later_time")
        # 获得旷工时间
        absent_time = group.get("absent_time")
    # 下班打卡
    if dict.get("start_or_end") == 0:
        # 获得打卡时间
        attends_sql = AttendsSqlMap.GET_PERIOD_BY_ID
        period = mysql_tools.select_one(attends_sql.format(**params))
        # 获得班次时间
        stop_time = str(period.get("stop_time"))
        if stop_time < "06:00:00":
            # 如果时间小于6点判断为第二天，需要添加24小时
            stop_time = (datetime.strptime(stop_time, "%T") + timedelta(hours=24)).strftime("%T")
        # 判断打卡的状态
        later_params = {
            "status_id": 10,
            "is_begin": False,
            "end_time": datetime.now(),
            "period_id": params.get("period_id")
        }
        if datetime.now().strftime("%T") < stop_time:
            # 设置早退
            later_params["status_id"] = 12
        else:
            # 正常情况下状态不变
            # 其他的情况是由定时任务执行的不需要接口执行
            later_params["status_id"] = "status_id"
        # 更新打卡
        period_sql = AttendsSqlMap.UPDATE_END_ATTEND
        # 根据时间和内容
        result = mysql_tools.execute_sql(period_sql.format(**later_params), commit=True)
        if isinstance(result, JsonResponse):
            return result
    # 上班打卡
    else:
        # 获得打卡时间
        attends_sql = AttendsSqlMap.GET_PERIOD_BY_ID
        period = mysql_tools.select_one(attends_sql.format(**params))
        # 获得班次时间
        start_time = period.get("start_time")
        # 如果迟到返回迟到
        attend_params = {
            "attends_time": datetime.now().strftime("%H:%M:%S"),
            "attends_user_id": params.get("user_id"),
            "attend_hmtime": datetime.now().strftime("%T"),
            "is_begin": 1,
            "start_time": datetime.now().strftime("%T"),
            "attends_date": datetime.now().strftime("%F"),
            "attendce_times": params.get("attend_times"),
            "period_id": period.get("period_id")
        }
        now_time = datetime.now().strftime("%T")
        # 是否有特殊情况
        attends_time = datetime.strptime(attend_params.get("attends_time"), "%H:%M:%S")
        # 生成打卡状态
        if attends_time < start_time:
            # 正常
            attend_params["status_id"] = 10
            attend_params["type_id"] = 0
            attend_sql = AttendsSqlMap.ADD_ATTEND.format(**attend_params)
            result = mysql_tools.execute_sql(attend_sql, commit=True)
            if isinstance(result, JsonResponse):
                return result
            return success_response(attend_params)
        else:
            logging.debug("public status")
            # 异常
            process_sql = AttendsSqlMap.GET_PROCESS_BY_START_TIME.format(
                start_time=now_time,
                process_user_id=params.get("user_id"))
            process = mysql_tools.select_one(process_sql)
            # 查询请假
            is_hoilday = not process is None
            attend_params["type_id"] = 0
            if is_hoilday:
                logging.debug("is holiday")
                if process.get("type_name") == "外出申请":
                    attend_params["status_id"] = 63
                elif process.get("type_name") == "出差申请":
                    attend_params["status_id"] = 64
                else:
                    attend_params["status_id"] = 65
                # 设置打卡为请假
                attend_params["status_id"] = 0
                
            if later_time:
                attend_params["is_begin"] = 1
                attend_params["start_time"] = datetime.now()
                if attends_time-timedelta(absent_time)<datetime.now():
                    # 设置为迟到
                    logging.debug("set status is usual")
                    attend_params["status_id"] = 74
                else:
                    # 设置为未签到
                    logging.debug("set status is usual")
                    attend_params["status_id"] = 74
                # attend_sql = AttendsSqlMap.ADD_ATTEND.format(**attend_params)
                # result = mysql_tools.execute_sql(attend_sql, commit=True)
            else:
                # 如果是缺勤是由定时任务生成，接口不需要进行处理
                pass
            if isinstance(result, JsonResponse):
                return result
            return success_response(attend_params)
    return success_response()


def attends_times(params):
    '''
    显示当天班次信息和打卡记录
    '''
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    if not params.get("user_id"):
        return err_response(210)
    params["now_date"] = datetime.now().strftime("%Y-%m-%d")  # 今天的年月日
    sql_plan = AttendsSqlMap.GET_MY_TIMES.format(**params)
    result = mysql_tools.select_all(sql_plan)  # 当天的班次信息,可能2个,可能1个
    if not result:
        return success_response([])
    else:
        for res in result:
            params["times_id"] = res.get("times_id")
            sql_record = AttendsSqlMap.GET_MY_RECORD.format(**params)
            record = mysql_tools.select_one(sql_record)  # 当天的打卡记录
            if not record or (record.get("work_time") is None and record.get("off_time") is None):
                record = {}
            res["attends_record"] = record
    return success_response(result)


def attend_planinfo(params):
    """
    考勤计划详情（每天签到的时候渲染页面）
    :param params:
    :return:
    """
    # 获得考勤计划
    # 获得考勤班次
    # 获得考勤组
    pass


@format_response
def index(request):
    global user_ip
    user_ip = get_ip(request)
    return com_views(request, {
        "attends_record": attends_record,  # 打卡
        "attends_times": attends_times,  # 我的当天班次信息
        "attend_planinfo": attend_planinfo
    })
